package com.milk.servlet;

import com.milk.Dao.MembersDao;
import com.milk.entity.Members;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


public class MemberManagementServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取操作类型
        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有会员
        }

        switch (action) {
            case "/add":
                showAddMemberForm(request, response); // 显示添加会员表单
                break;
            case "/edit":
                showEditMemberForm(request, response); // 显示编辑会员表单
                break;
            case "/delete":
                deleteMember(request, response); // 删除会员
                break;
            case "/search":
                searchMember(request, response); // 搜索会员
                break;
            default:
                listAllMembers(request, response); // 默认列出所有会员
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取操作类型
        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有会员
        }

        switch (action) {
            case "/add":
                addMember(request, response); // 添加会员
                break;
            case "/update":
                updateMember(request, response); // 更新会员
                break;
            default:
                // 处理其他不支持的POST请求
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    // 显示添加会员表单
    private void showAddMemberForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 转发到添加会员表单页面
        request.getRequestDispatcher("/add_member_form.jsp").forward(request, response);
    }

    // 显示编辑会员表单
    private void showEditMemberForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取要编辑的会员ID
        int id = Integer.parseInt(request.getParameter("id"));

        // 根据ID查询会员信息
        Members member = MembersDao.findById(id);
        if (member != null) {
            request.setAttribute("member", member);
            // 转发到编辑会员表单页面
            request.getRequestDispatcher("/edit_member_form.jsp").forward(request, response);
        } else {
            // 未找到对应的会员，返回错误信息
            response.sendRedirect(request.getContextPath() + "/members?error=notfound");
        }
    }

    // 删除会员
    private void deleteMember(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取要删除的会员ID
        int id = Integer.parseInt(request.getParameter("id"));

        // 调用 MembersDao 的方法删除会员
        int result = MembersDao.deleteById(id);
        if (result > 0) {
            // 删除成功，重定向到会员列表页面
            response.sendRedirect(request.getContextPath() + "/members");
        } else {
            // 删除失败，返回错误信息
            response.sendRedirect(request.getContextPath() + "/members?error=delete");
        }
    }

    // 搜索会员
    private void searchMember(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取搜索关键字
        String userName = request.getParameter("searchUserName");

        // 调用 MembersDao 的方法进行模糊搜索
        List<Members> members = MembersDao.searchByUserName(userName);
        request.setAttribute("members", members);

        // 转发到会员列表页面（假设为member_management.jsp）
        request.getRequestDispatcher("/member_management.jsp").forward(request, response);
    }

    // 列出所有会员
    private void listAllMembers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询所有会员信息
        List<Members> members = MembersDao.findAll();
        request.setAttribute("members", members);

        // 转发到会员列表页面（假设为member_management.jsp）
        request.getRequestDispatcher("/member_management.jsp").forward(request, response);
    }

    // 添加会员
    private void addMember(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取会员信息参数
        String userName = request.getParameter("userName");
        String phoneNumber = request.getParameter("phoneNumber");
        String pointsStr = request.getParameter("points");

        // 表单验证
        if (userName == null || userName.isEmpty() || phoneNumber == null || phoneNumber.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/members/add?error=empty");
            return;
        }

        // 处理积分参数
        int points = 0; // 默认值为 0
        if (pointsStr != null && !pointsStr.isEmpty()) {
            try {
                points = Integer.parseInt(pointsStr);
            } catch (NumberFormatException e) {
                response.sendRedirect(request.getContextPath() + "/members/add?error=invalidpoints");
                return;
            }
        }

        // 创建 Member 对象
        Members member = new Members();
        member.setUserName(userName);
        member.setPhoneNumber(phoneNumber);
        member.setPoints(points);

        // 调用 MembersDao 的方法添加会员
        int result = MembersDao.add(member);
        if (result > 0) {
            // 添加成功，重定向到会员列表页面
            response.sendRedirect(request.getContextPath() + "/members");
        } else {
            // 添加失败，返回错误信息
            response.sendRedirect(request.getContextPath() + "/members/add?error=addfailed");
        }
    }

    // 更新会员
    private void updateMember(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取会员信息参数
        int id = Integer.parseInt(request.getParameter("id"));
        String userName = request.getParameter("userName");
        String phoneNumber = request.getParameter("phoneNumber");
        String pointsStr = request.getParameter("points");

        // 表单验证
        if (userName == null || userName.isEmpty() || phoneNumber == null || phoneNumber.isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/members/edit?id=" + id + "&error=empty");
            return;
        }

        // 处理积分参数
        int points = 0; // 默认值为 0
        if (pointsStr != null && !pointsStr.isEmpty()) {
            try {
                points = Integer.parseInt(pointsStr);
            } catch (NumberFormatException e) {
                response.sendRedirect(request.getContextPath() + "/members/edit?id=" + id + "&error=invalidpoints");
                return;
            }
        }

        // 创建 Member 对象
        Members member = new Members();
        member.setId(id);
        member.setUserName(userName);
        member.setPhoneNumber(phoneNumber);
        member.setPoints(points);

        // 调用 MembersDao 的方法修改会员信息
        int result = MembersDao.update(member);
        if (result > 0) {
            // 修改成功，重定向到会员列表页面
            response.sendRedirect(request.getContextPath() + "/members");
        } else {
            // 修改失败，返回错误信息
            response.sendRedirect(request.getContextPath() + "/members/edit?id=" + id + "&error=updatefailed");
        }
    }
}